package com.chaoge.web.controller.store;

import com.chaoge.domain.store.Catalog;
import com.chaoge.domain.store.Company;
import com.chaoge.domain.store.Question;
import com.chaoge.domain.store.Course;
import com.chaoge.utils.BeanUtil;
import com.chaoge.web.controller.BaseServlet;
import com.github.pagehelper.PageInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;


@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet {
    //private QuestionService questionService=new QuestionServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operation = request.getParameter("operation");
        switch (operation){
            case "list":
                this.list(request,response);
                break;
            case "toAdd":
                this.toAdd(request,response);
                break;
            case "save":
                try {
                    this.save(request,response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "toEdit":
                this.toEdit(request,response);
                break;
            case "edit":
                try {
                    this.edit(request,response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "delete":
                this.delete(request,response);
                break;
            case "toUpload":
                this.toUpload(request,response);
                break;
            case "testFileUpload":
                try {
                    this.testFileUpload(request,response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "downloadReport":
                this.downloadReport(request,response);
                break;
        }
    }

    private void downloadReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //返回文件的数据类型是xslx类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //获取流对象
        ByteArrayOutputStream report = questionService.getReport();
        //获取响应流对象
        ServletOutputStream outputStream = response.getOutputStream();
        report.writeTo(outputStream);
        outputStream.flush();
        outputStream.close();
        report.close();
    }

    private void testFileUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.确认该操作是否支持文件上传操作，enctype="multipart/form‐data"
        if (ServletFileUpload.isMultipartContent(request)){
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory=new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload=new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for(FileItem fileItem:fileItems){
                //5.当前表单是否是文件表单
                if(!fileItem.isFormField()){
                    //6.从临时存储文件的地方将内容写入到指定位置
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"),fileItem.getName()));
                }
            }


        }
    }

    private void toUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/pages/store/question/testFileUpload.jsp").forward(request,response);
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取数据
        Question question= BeanUtil.fillBean(request, Question.class);
        //将数据传到questionService层
        questionService.delete(question);
        //跳转到List页面
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.确认该操作是否支持文件上传操作，enctype="multipart/form‐data"
        if (ServletFileUpload.isMultipartContent(request)){
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory=new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload=new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            boolean flag=false;
            for (FileItem item:fileItems){
                if (StringUtils.isNoneBlank(item.getName())){
                    flag=true;
                    break;
                }
            }
            //获取数据
            Question question= BeanUtil.fillBean(fileItems,Question.class);
            System.out.println(question);
            //将数据传到questionService层
            questionService.update(question,flag);

            for(FileItem fileItem:fileItems){
                //5.当前表单是否是文件表单
                if(!fileItem.isFormField()){
                    //6.从临时存储文件的地方将内容写入到指定位置
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"),question.getId()));
                }
            }

        }
        //跳转到List页面
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ServletException {
        //获取id
        String id = request.getParameter("id");
        //查询单个数据
        Question question = questionService.findById(id);
        List<Course> all = courseService.findAll();
        request.setAttribute("courseList",all);
        List<Company> all1 = companyService.findAll();
        request.setAttribute("companyList",all1);

        List<Catalog> all2 = catalogService.findAll();
        request.setAttribute("catalogList",all2);
        //设置数据
        request.setAttribute("question",question);
        //页面跳转
        request.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(request,response);
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.确认该操作是否支持文件上传操作，enctype="multipart/form‐data"
        if (ServletFileUpload.isMultipartContent(request)){
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory=new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload=new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            boolean flag=false;
            for (FileItem item:fileItems){
                if (StringUtils.isNoneBlank(item.getName())){
                    flag=true;
                    break;
                }
            }
            //获取数据
            Question question= BeanUtil.fillBean(fileItems,Question.class);

            //将数据传到questionService层
            String id =questionService.save(question,flag);

            for(FileItem fileItem:fileItems){
                //5.当前表单是否是文件表单
                if(!fileItem.isFormField()){
                    //6.从临时存储文件的地方将内容写入到指定位置
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"),id));
                }
            }

        }
        //跳转到List页面
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
        List<Course> all = courseService.findAll();
        request.setAttribute("courseList",all);

        List<Company> all1 = companyService.findAll();
        request.setAttribute("companyList",all1);

        List<Catalog> all2 = catalogService.findAll();
        request.setAttribute("catalogList",all2);

        //页面跳转
        request.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(request,response);
    }

    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //进入列表页
        //获取数据
        int page=1;
        int size=5;
        if (StringUtils.isNotBlank(request.getParameter("page"))){
            page=Integer.parseInt(request.getParameter("page"));
        }
        if (StringUtils.isNotBlank(request.getParameter("size"))){
            size=Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all = questionService.findAll(page, size);
        //将数据保存
        request.setAttribute("page",all);
        //页面跳转
        request.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}